function [h, hfig] = multiplot(varargin)
% Arguments  = (figname, m, n, k, box, margins, annotations, 'multi')
% multiplot  -  multiplot(figurename, m, n, k, box)
% make a multiple plot screen for archival plots.
% of mxn plot areas, each with a stacked set of k plots.
% where k may correspond to different kinds of signals (different axes)
% if k is an array then length(k) plots are stacked, but the
% relative sizes are determined by the values in k: e.g., 
% k = [0.3, 0.2, 0.5] would make the plots take 30, 20 and 50% of the space available.
% box : this restricts the multiplot space to a fractional window of the
% current figure window, as a position. Example: [0 0 1 1] is full sized. 
% [0 0 1 0.5] would fill only the lower half of the window.
% the plot is placed in hfig, unless hfig is empty, in which case a default figure
% is created.
% returns:
% [h, hfig]
% where h is the list of handles to the plots
% hfig is the handle to the figure
% margins (optional) specifies space around the graphs - specified in
% percent: margins is a 2-element vector
% annotations adds annotations to the figure
% 'multi' causes the figure to NOT be cleared, allowing muliptle
% "multiplots" on one page.
%

h = []; % list of handles to each of the plots created.

figname = varargin{1};
m = varargin{2};
n = varargin{3};
k = varargin{4};
if(nargin > 4)
    box = varargin{5};
    if(isempty(box))
        box = [  0 0 1 1 ];
    end;
else
    box = [0 0 1 1];
end;
if(length(box) < 4)
    fprintf(2, 'multiplot box is a 4-element position vector\n');
    return;
end;
if(nargin > 5)
    margins = varargin{6};
else
    margins = [1 4];
end;
annflag = 0;
anntext = {};
if(nargin > 6)
    if(isnumeric(varargin{6}))
        annflag = 1; % automatic
    end;
    if(iscell(varargin{6}))
        annflag = 1;
        anntext = varargin{6};
    end;
end;
mmplot = 0; % normally, clear every time
if(nargin > 7)
    if(strcmpi(varargin{7}, 'multi'))
        mmplot = 1;
    end;
end;

    
if(~isempty(figname) && ~ishandle(figname(1)) && ischar(figname))
    hfig = findobj('Tag', figname);
else
    hfig = [];
end;
if(ishandle(figname))
    hfig = figname;
end;
if(isempty(hfig) || ~ishandle(hfig))
   hfig = figure('Tag', figname, 'name', figname, 'NumberTitle', 'off');
end;
figure(hfig);

set(gcf, 'Renderer', 'OpenGL');
if(~mmplot)
    clf; % if mmplot is set, allow multiple multiplots on a page... 
end;

if(nargin < 4)
   fprintf(2, 'multiplot requires at least 4 arguments\n');
   return;
end;

if(m <= 0 || n <= 0)
   fprintf(2, 'multiplot requires m and n > 0\n');
   return;
end;

if(length(k) == 1 && k < 1)
   fprintf(2, 'multiplot requires k >= 1\n');
   return;
end;

% definitions:
h_margin = (margins(2)/100)*box(3); % horizontal margin
v_margin = (margins(2)/100)*box(4); % vertical margin

space = margins(1)/100; % space between plots.

% compute horizontal width for each plot:
hw = box(3)*((1.0 - 2*h_margin - space*(m-1)) / m);

% compute vertical size of each plot:
vw = box(4)*((1.0 - 2*v_margin - space*(n-1)) / n);

%mxn = m*n; % total plot areas on the screen.

% figure the internal subplot structure
if(length(k) > 1)
   sk = sum(k);
   k = k/sk; % allows use of different numbers in generating the subplots...
   yh = k;
else
   yh = 1;
end;
h = zeros(n*m, length(yh));
ha = h;
icount = 1;
for ni = 1:n
   y0 = 1-((1-box(2)) - (v_margin + ((n-ni)*vw + (n-ni)*space)));
   for mi = 1:m
      x0 = box(1) + h_margin + (mi-1)*hw + (mi-1) * space;
      hpos = mi + (ni-1) * m;
      yp = y0;
      for j = 1:length(yh)
          figure(hfig); % just to be sure
          h(hpos, j) = axes('Position', [x0, yp, hw, vw*yh(j)], 'FontSize', 10);
          if(annflag) % include an annotation to left top of graph?
              if(~isempty(anntext))
                  if(length(anntext) <= icount)
                      ha(icount) = annotate('textbox', [x0, yp, 0.1, 0.1]);
                      set(ha(icount), 'String', anntext{icount}, 'fontsize', 18, ...
                          'linestyle', 'none');
                  end;
              else
                  ha(icount) = annotation('textbox', [x0-h_margin/1.33, yp+vw-v_margin/3.5, 0.1, 0.1]);
                  if(n > m)
                      indice = ni + (mi-1)*n;
                  else
                      indice = mi + (ni-1)*m;
                  end;
                  set(ha(icount), 'String', char(64+indice), 'fontsize', 18, ...
                      'linestyle', 'none'); % sequential lettering
              end;
          end;  
                 
         yp = yp + vw*yh(j);
         if(ni < n || j > 1);
            set(gca, 'XTickLabel', '');
         end;
         if(mi > 1 )
            set(gca, 'YTickLabel', '');
         end;
         
      end;
    icount = icount + 1;
   end;
  
end;
